package com.example.feidaolumanager.pages.ui.index

import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.itemsIndexed
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ListAlt
import androidx.compose.material.icons.filled.Task
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.paint
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import cn.idesign.cui.statefullayout.StatefulLayout
import cn.idesign.cui.statefullayout.StatefulStatus
import cn.idesign.cui.statefullayout.rememberStatefulState
import com.example.feidaolumanager.R
import com.example.feidaolumanager.databinding.FragmentIndexBinding
import com.example.feidaolumanager.pages.ui.machine.MachinesViewModel
import com.example.feidaolumanager.pojo.User
import com.example.feidaolumanager.viewModel.MainViewModel

class IndexFragment : Fragment() {

    private lateinit var viewModel: IndexViewModel
    private lateinit var mainViewModel: MainViewModel

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        val inflate = FragmentIndexBinding.inflate(inflater, container, false)

        val machinesViewModel = ViewModelProvider(requireActivity())[MachinesViewModel::class.java]

        val user: User? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            activity?.intent?.getSerializableExtra("user", User::class.java)
        } else {
            activity?.intent?.getSerializableExtra("user") as User?
        }

        if (user != null) {
            machinesViewModel.getMachines(user)
        } else {
            Log.e(this.toString(), "onCreateView: 用户信息异常的为空")
        }

        machinesViewModel.status.observe(viewLifecycleOwner) {
            if (it == StatefulStatus.NetError) {
                Toast.makeText(context, "网络超时", Toast.LENGTH_SHORT).show()
            }
        }
        machinesViewModel.getPmAvg(user)

        inflate.tvCompose.setContent {

            val scrollState = rememberScrollState()
            Column(
                modifier = Modifier
                    .padding(bottom = 60.dp)
                    .fillMaxHeight()
                    .background(color = Color(246, 247, 248))
                    .verticalScroll(state = scrollState)
            ) {


                Box {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(170.dp)
                            .paint(
                                painter = painterResource(
                                    id = R.drawable.bg,
                                ), contentScale = ContentScale.FillBounds
                            )
                    ) {
                        Spacer(modifier = Modifier.height(80.dp))
                        Text(
                            text = "非道路机械管理平台",
                            color = Color.White,
                            fontSize = 24.sp,
                            fontWeight = FontWeight.W700,
                            modifier = Modifier.padding(start = 20.dp)
                        )
                        Text(
                            text = "工地非道路移动机械管理平台移动端",
                            color = Color.White,
                            fontSize = 10.sp,
                            modifier = Modifier.padding(start = 20.dp)
                        )
                    }
                    LazyVerticalGrid(
                        columns = GridCells.Fixed(4),
                        modifier = Modifier
                            .height(260.dp)
                            .padding(start = 10.dp, end = 10.dp, top = 140.dp)
                            .clip(shape = RoundedCornerShape(6.dp))
                            .background(color = Color.White),
                        contentPadding = PaddingValues(10.dp, 10.dp, 10.dp, 10.dp)
                    ) {
                        itemsIndexed(MyIconListItem.list) { index, it ->
                            TextButton(
                                contentPadding = PaddingValues(0.dp),
                                onClick = {
                                    val navController = findNavController()
                                    when (index) {
                                        0 -> {
                                            Log.e(
                                                this.toString(),
                                                "onCreateView: ${mainViewModel.hashCode()}"
                                            )
                                            navController.navigate(R.id.navigation_to_task)
                                            mainViewModel.ifShowMenu.value = false
                                        }

                                        1 -> {
                                            navController.navigate(R.id.navigation_to_machine_manage)
                                            mainViewModel.ifShowMenu.value = false
                                        }

                                        else -> {}
                                    }
                                },
                                shape = RoundedCornerShape(0.dp)
                            ) {
                                Column(horizontalAlignment = Alignment.CenterHorizontally) {
                                    Icon(it.icon, "", tint = Color.Black)
                                    Text(
                                        text = it.text, color = Color.Black
                                    )
                                }
                            }
                        }
                    }
                }
                Spacer(modifier = Modifier.height(10.dp))


                Text(
                    text = "数据统计",
                    fontWeight = FontWeight.W800,
                    fontSize = 20.sp,
                    modifier = Modifier.padding(start = 10.dp, end = 10.dp, top = 10.dp)
                )

                Spacer(modifier = Modifier.height(10.dp))

                LazyVerticalGrid(columns = GridCells.Fixed(3),
                    modifier = Modifier.height(110.dp),
                    contentPadding = PaddingValues(horizontal = 10.dp),
                    content = {
                        itemsIndexed(
                            listOf(
                                "设备总数",
                                "工作设备数",
                                "静止设备数",
                            )
                        ) { index: Int, it: String ->
                            when (index) {
                                1 -> {
                                    MachineCountCard(
                                        name = it,
                                        count = machinesViewModel
                                            .workMachineCount.intValue,
                                        countColor = Color.Green,
                                        activity = this@IndexFragment.activity
                                    )
                                }

                                2 -> {
                                    MachineCountCard(
                                        name = it, count = machinesViewModel
                                            .noWorkMachineCount.intValue,
                                        countColor = Color.Gray,
                                        activity = this@IndexFragment.activity
                                    )
                                }

                                0 -> {
                                    MachineCountCard(
                                        name = it, count = machinesViewModel
                                            .machineList.value.size,
                                        countColor = Color.White,
                                        activity = this@IndexFragment.activity
                                    )
                                }

                                else -> {}
                            }
                        }
                    })


                Text(
                    text = "统计列表",
                    fontWeight = FontWeight.W800,
                    fontSize = 20.sp,
                    modifier = Modifier.padding(start = 10.dp, end = 10.dp, top = 10.dp)
                )

                for (i in 0..0) {
                    Spacer(modifier = Modifier.height(10.dp))

                    Column(
                        modifier = Modifier
                            .padding(horizontal = 10.dp)
                            .clip(RoundedCornerShape(6.dp))
                            .background(color = Color.White)
                    ) {
                        Text(
                            text = "工地PM10平均值(ug/m³)",
                            fontWeight = FontWeight.W800,
                            fontSize = 16.sp,
                            modifier = Modifier.padding(start = 10.dp, end = 10.dp, top = 10.dp)
                        )

                        Divider()

                        val state = rememberStatefulState(initialState = StatefulStatus.Content)

                        if (machinesViewModel.areaPm25ValueAvgList.isEmpty()) {
                            state.currentState = StatefulStatus.Empty
                        } else {
                            state.currentState = StatefulStatus.Content
                        }

                        StatefulLayout(
                            state = state
                        ) {
                            LazyColumn(
                                modifier = Modifier.height(
                                    (machinesViewModel.areaPm25ValueAvgList.size * 26).dp
                                ),
                                contentPadding = PaddingValues(10.dp),
                            ) {
                                items(machinesViewModel.areaPm25ValueAvgList) { pmAvgInfo ->
                                    Row(
                                        horizontalArrangement = Arrangement.SpaceBetween,
                                        modifier = Modifier.fillMaxWidth()
                                    ) {
                                        Text(text = pmAvgInfo.name)
                                        Text(text = pmAvgInfo.pm25.toString())
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        return inflate.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel = ViewModelProvider(this)[IndexViewModel::class.java]
        mainViewModel = ViewModelProvider(requireActivity())[MainViewModel::class.java]
        Log.e(this.toString(), "onViewCreated: ${viewModel.hashCode()}")
        // TODO: Use the ViewModel
    }

}

class MyIconListItem(val icon: ImageVector, val text: String) {

    companion object {
        val list = listOf(
            MyIconListItem(Icons.Default.Task, "任务"),
            MyIconListItem(Icons.Default.ListAlt, "电子标签")
        )
    }
}